import axios from 'axios';
import qs from 'qs';
import { ElMessage } from 'element-plus';
import store from '@/store';
import tools from '@/utils/tools';

const { getToken } = tools;

const axiosConfig = {
    baseURL: `${process.env.VUE_APP_BASE_API}/admin-api`,
    timeout: 30 * 1000,
};

const Axios = axios.create(axiosConfig);

Axios.interceptors.request.use(
    (config) => {
        // get参数编码
        if ((config.method || '').toUpperCase() === 'GET' && config.params) {
            const paramsStr = qs.stringify(config.params, { allowDots: true });
            if (paramsStr) config.url = `${config.url}?${paramsStr}`;
            config.params = {};
        }
        config.headers.Authorization = `Bearer ${getToken()}`;
        window.NProgress.start();
        return config;
    },
    (error) => {
        window.NProgress.done();
        Promise.reject(error);
    },
);

// 响应拦截
Axios.interceptors.response.use(
    async (res) => {
        window.NProgress.done();
        const { code, message, msg } = res.data || {};

        // 返回成功响应
        if (res.config.responseType === 'blob' || String(code) === '0') return res;

        if (String(code) === '401') store.dispatch('handleAskRelogin');

        // 错误提示拦截
        const messageTip = msg || message || '服务器响应失败，请稍后再试';
        ElMessage({ type: 'error', message: messageTip });

        return Promise.reject(res);
    },
    (error) => {
        window.NProgress.done();
        ElMessage({ type: 'error', message: '服务器内部异常' });
        return Promise.reject(error);
    },
);

export default Axios;
